<template>
  <div class="container">
    <el-card>
      <div class="title">试题录入</div>
      <div class="form">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
        >
          <el-form-item label="学科" prop="subjectID">
            <!-- 无id -->
            <el-select
              style="width: 400px"
              v-model="ruleForm.subjectID"
              placeholder="请选择"
              @visible-change="subjectHandle"
              :style="{ display: id ? 'none' : 'block' }"
            >
              <el-option
                v-for="(item, index) in subjectOptions"
                :key="index"
                :label="item.subjectName"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- 有id -->
            <el-select
              style="width: 400px"
              v-model="ruleForm.subjectName"
              placeholder="请选择"
              @visible-change="subjectHandle"
              :style="{ display: id ? 'block' : 'none' }"
            >
              <el-option
                v-for="(item, index) in subjectOptions"
                :key="index"
                :label="item.subjectName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录" prop="catalogID">
            <!-- 无id -->
            <el-select
              style="width: 400px"
              v-model="ruleForm.catalogID"
              placeholder="请选择"
              @visible-change="catalogHandle"
              :style="{ display: id ? 'none' : 'block' }"
            >
              <el-option
                v-for="(item, index) in catalogOptions"
                :key="index"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- 有id -->
            <el-select
              style="width: 400px"
              v-model="ruleForm.directoryName"
              placeholder="请选择"
              @visible-change="catalogHandle"
              :style="{ display: id ? 'block' : 'none' }"
            >
              <el-option
                v-for="(item, index) in catalogOptions"
                :key="index"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业" prop="enterpriseID">
            <!-- 无id -->
            <el-select
              style="width: 400px"
              v-model="ruleForm.enterpriseID"
              placeholder="请选择"
              @visible-change="enterpriseHandle"
              :style="{ display: id ? 'none' : 'block' }"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- 有id -->
            <el-select
              style="width: 400px"
              v-model="ruleForm.direction"
              placeholder="请选择"
              @visible-change="enterpriseHandle"
              :style="{ display: id ? 'block' : 'none' }"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市二级联动 -->
          <el-form-item label="城市" prop="province">
            <AreaData @city="selectRegion" :cityArea="cityAreas" />
          </el-form-item>
          <el-form-item label="方向" prop="direction">
            <el-select
              style="width: 400px"
              v-model="ruleForm.direction"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in questionDirection"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型" prop="questionType">
            <el-radio-group v-model="ruleForm.questionType">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度" prop="difficulty">
            <el-radio-group v-model="ruleForm.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干" prop="question">
            <QuillEditor
              @RichText="richText"
              ref="richText"
              :question="questions"
            />
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项" :style="{ display: choiceIpt }">
            <el-row v-for="(item, index) in ruleForm.options" :key="index">
              <el-col :span="1">
                <!-- v-model="item.code" -->
                <el-radio-group v-model="singleChoice">
                  <el-radio
                    :label="option[index]"
                    :style="{
                      display: questionType == '1' ? 'block' : 'none',
                    }"
                  ></el-radio>
                  <el-checkbox
                    v-model="item.isRight"
                    :label="option[index]"
                    :style="{
                      display: questionType == '1' ? 'none' : 'block',
                    }"
                  ></el-checkbox>
                </el-radio-group>
              </el-col>

              <el-col :span="1">
                <el-input
                  type="text"
                  style="width: 200px"
                  v-model="item.title"
                ></el-input>
              </el-col>
              <el-col :span="1">
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="item.img" :src="item.img" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-button type="danger" disabled>+增加选项与答案</el-button>
            </el-row>
          </el-form-item>
          <el-form-item label="解析视频" prop="videoURL">
            <el-input
              style="width: 400px"
              v-model="ruleForm.videoURL"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="答案解析" prop="answer">
            <QuillEditor
              @RichText="richText1"
              ref="richText1"
              :question="answer"
            />
          </el-form-item>
          <el-form-item label="题目备注" prop="remarks">
            <el-input
              style="width: 400px"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="ruleForm.remarks"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="试题标签" prop="tags">
            <el-select
              style="width: 400px"
              v-model="ruleForm.tags"
              placeholder="请选择"
            >
              <el-option
                v-for="item in tagOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">确认提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import QuillEditor from '../components/RichText'
import { list } from '@/api/hmmm/subjects.js'
import { list as enterpriseList } from '@/api/hmmm/companys.js'
import { list as catalogList } from '@/api/hmmm/directorys.js'
import AreaData from '../components/AreaData'
import { add, update, detail } from '@/api/hmmm/questions.js'
export default {
  components: {
    QuillEditor,
    AreaData
  },
  data() {
    return {
      id: this.$route.query.id,
      singleChoice: '',
      choiceIpt: 'block',
      questionDirection: [
        'o2o',
        '外包服务',
        '企业服务',
        '互联网金融',
        '企业咨询',
        '互联网',
        '电子商务',
        '其他'
      ],
      // 试题答案选项
      option: ['A', 'B', 'C', 'D'],
      // 试题标签选项
      tagOption: [],
      // 学科选项
      subjectOptions: [],
      // 目录选项
      catalogOptions: [],
      // 企业选项
      enterpriseList: [],
      ruleForm: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选项
        options: [
          {
            // 代码
            code: 'A',
            // 标题
            title: '',
            // 图片url
            img: '',
            // 是否正确答案
            isRight: 0
          },
          {
            // 代码
            code: 'B',
            // 标题
            title: '',
            // 图片url
            img: '',
            // 是否正确答案
            isRight: 0
          },
          {
            // 代码
            code: 'C',
            // 标题
            title: '',
            // 图片url
            img: '',
            // 是否正确答案
            isRight: 0
          },
          {
            // 代码
            code: 'D',
            // 标题
            title: '',
            // 图片url
            img: '',
            // 是否正确答案
            isRight: 0
          }
        ],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [{ required: true, message: '请填写题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请填写答案解析', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.id) {
      this.getlist()
    }
  },
  methods: {
    async getlist() {
      const res = await detail({ id: this.id })
      res.data.options.forEach(item => {
        item.isRight = item.isRight === 0
      })
      console.log(res.data)
      this.ruleForm = res.data
    },
    submitForm() {
      this.ruleForm.question = this.$refs.richText.content.replace(
        /<\/?[^>]*>/g,
        ''
      )
      this.ruleForm.answer = this.$refs.richText1.content.replace(
        /<\/?[^>]*>/g,
        ''
      )
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          try {
            if (!this.id) {
              add(this.ruleForm).then(() => {
                this.$message({
                  message: '恭喜你，基础题库添加成功！',
                  type: 'success'
                })
                this.$refs.ruleForm.resetFields()
                this.$router.push('/questions/list')
              })
            } else {
              // this.ruleForm.subjectID = this.ruleForm.subjectName
              // this.ruleForm.catalogID = this.ruleForm.directoryName
              update({ id: this.id, ...this.ruleForm }).then(() => {
                this.$message({
                  message: '恭喜你，修改题库添加成功！',
                  type: 'success'
                })
                this.$refs.ruleForm.resetFields()
                this.$router.push('/questions/list')
              })
            }
          } catch (error) {
            console.log(error.message)
          }
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async subjectHandle() {
      const res = await list({ page: 1, pagesize: 100 })
      this.subjectOptions = res.data.items
    },
    async catalogHandle() {
      const res = await catalogList()
      this.catalogOptions = res.data.items
    },
    async enterpriseHandle() {
      const res = await enterpriseList({ pagesize: 10000 })
      this.enterpriseList = res.data.items
    },
    // 城市组件传值
    selectRegion(obj) {
      this.ruleForm.province = obj.city
      this.ruleForm.city = obj.area
    },
    richText(p) {
      this.ruleForm.question = p
    },
    richText1(p) {
      this.ruleForm.area = p
    }
  },
  computed: {
    questionType() {
      return this.ruleForm.questionType
    },
    cityAreas() {
      return {
        area: this.ruleForm.city,
        city: this.ruleForm.province
      }
    },
    questions() {
      return this.ruleForm.question
    },
    answer() {
      return this.ruleForm.answer
    }
  },
  watch: {
    questionType(newVal) {
      switch (newVal) {
        case '1':
          this.choiceIpt = 'block'
          break
        case '2':
          this.choiceIpt = 'block'

          break
        case '3':
          this.choiceIpt = 'none'

          break
      }
    },
    singleChoice(newVal) {
      switch (newVal) {
        case 'A':
          this.ruleForm.options[0].isRight = true
          this.ruleForm.options[1].isRight = false
          this.ruleForm.options[2].isRight = false
          this.ruleForm.options[3].isRight = false
          break
        case 'B':
          this.ruleForm.options[0].isRight = false
          this.ruleForm.options[1].isRight = true
          this.ruleForm.options[2].isRight = false
          this.ruleForm.options[3].isRight = false
          break
        case 'C':
          this.ruleForm.options[0].isRight = false
          this.ruleForm.options[1].isRight = false
          this.ruleForm.options[2].isRight = true
          this.ruleForm.options[3].isRight = 0
          break
        case 'D':
          this.ruleForm.options[0].isRight = false
          this.ruleForm.options[1].isRight = false
          this.ruleForm.options[2].isRight = true
          this.ruleForm.options[3].isRight = false
          break
        default:
          break
      }
    }
  }
}
</script>

<style scoped>
.container {
  margin: 20px 20px;
  background-color: #fff;
}

.container .title {
  padding: 0 20px 18px;
  margin: 0 -20px;
  border-bottom: 1px solid #ebeef5;
}

.container .form {
  padding: 20px 0;
}

::v-deep .ql-editor {
  min-height: 200px;
}

.avatar-uploader {
  transform: translate(160px, -10px);
}

.avatar-uploader .el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
}
.el-form-item .el-row {
  margin: 0 0 10px;
}
</style>
